package ru.pb.dao.auth.mysql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import ru.pb.auth.dao.IpsDAO;
import ru.pb.auth.model.IP;
import ru.pb.global.dao.annotations.DAO;
import ru.pb.global.dbc.DatabaseFactory;
import ru.pb.global.dbc.DatabaseUtils;

/**
 * @author Felixx
 */
@DAO(database = "MySQL")
public class IpsDAOImpl implements IpsDAO
{
	private static final Logger _log = Logger.getLogger(IpsDAOImpl.class);

	@Override
	public List<IP> select()
	{
		List<IP> ips = new ArrayList<IP>();
		Connection con = null;
		PreparedStatement statement = null;
		ResultSet rset = null;

		try
		{
			con = DatabaseFactory.getInstance().newConnection();
			statement = con.prepareStatement("SELECT * FROM ips ORDER BY white");
			rset = statement.executeQuery();
			while(rset.next())
			{
				String ip = rset.getString("ip");
				String admin = rset.getString("admin");
				long addDate = rset.getLong("add_date");
				long endDate = rset.getLong("end_date");
				boolean white = rset.getByte("white") == 1;

				IP ipT = new IP(ip, admin, addDate, endDate, white);

				ips.add(ipT);
			}
		}
		catch(Exception e)
		{
			_log.info("Exception: " + e, e);
		}
		finally
		{
			DatabaseUtils.closeDatabaseCSR(con, statement, rset);
		}

		return ips;
	}

	@Override
	public void insert(IP ip)
	{
		Connection con = null;
		PreparedStatement statement = null;
		try
		{
			con = DatabaseFactory.getInstance().newConnection();
			statement = con.prepareStatement("INSERT INTO ips (ip, admin, add_date, end_date, white) VALUES (?,?,?,?,?)");
			statement.setString(1, ip.getIp());
			statement.setString(2, ip.getAdmin());
			statement.setLong(3, ip.getAddTime());
			statement.setLong(4, ip.getEndTime());
			statement.setByte(5, ip.isWhite() ? (byte) 1 : (byte) 0);
			statement.executeUpdate();
		}
		catch(Exception e)
		{
			_log.info("Exception: " + e, e);
		}
		finally
		{
			DatabaseUtils.closeDatabaseCS(con, statement);
		}
	}

	@Override
	public void delete(String t)
	{
		Connection con = null;
		PreparedStatement statement = null;
		try
		{
			con = DatabaseFactory.getInstance().newConnection();
			statement = con.prepareStatement("DELETE FROM ips WHERE ip=?");
			statement.setString(1, t);
			statement.executeUpdate();
		}
		catch(Exception e)
		{
			_log.info("Exception: " + e, e);
		}
		finally
		{
			DatabaseUtils.closeDatabaseCS(con, statement);
		}
	}
}